package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.upmp.domain.UpmpMenu;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpRoleMenu;
import cc.rengu.redp.bizimpl.upmp.dao.UpmpRoleMenuMapper;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpMenuService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpRoleMenuService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author System
 */
@Slf4j
@Service("upmpRoleMenuService")
@DS("upmp")
public class UpmpRoleMenuServiceImpl extends ServiceImpl<UpmpRoleMenuMapper, UpmpRoleMenu> implements IUpmpRoleMenuService {

    @Autowired
    IUpmpMenuService menuService;

    @Override
    @Transactional
    public void deleteRoleMenusByRoleId(String[] roleIds) {
        List<String> list = Arrays.asList(roleIds);
        baseMapper.delete(new LambdaQueryWrapper<UpmpRoleMenu>().in(UpmpRoleMenu::getRoleId, list));
    }

    @Override
    @Transactional
    public void deleteRoleMenusByMenuId(String[] menuIds) {
        List<String> list = Arrays.asList(menuIds);
        baseMapper.delete(new LambdaQueryWrapper<UpmpRoleMenu>().in(UpmpRoleMenu::getMenuId, list));
    }

    @Override
    public List<UpmpRoleMenu> getRoleMenusByRoleId(String roleId) {
        //加载角色菜单时过滤掉所有父节点
        QueryWrapper<UpmpMenu> lqw = new QueryWrapper<>();
        lqw.select("DISTINCT parent_id");
        List<UpmpMenu> parentMenus = menuService.list(lqw);
        List<String> parentMenuIds = new ArrayList<>();
        parentMenus.forEach(menu ->{
                log.info("menu:{}",menu);
                if(!ObjectUtils.isEmpty(menu)){
                    parentMenuIds.add(menu.getParentId());
                }
            }
        );
        return baseMapper.selectList(new LambdaQueryWrapper<UpmpRoleMenu>()
                .eq(UpmpRoleMenu::getRoleId, roleId)
                .notIn(UpmpRoleMenu::getMenuId, parentMenuIds));
    }
}
